package cn.xiaolang.function.dom4j;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.junit.Test;

import cn.xiaolang.domain.Member;

public class PojoAndXml {

    @Test
    public void testMember2Xml() {
        Member member = new Member();
        member.setSid("10010");
        member.setSname("小黑");
        member.setCourse(2500);
        String xml = Member2Xml(member);
        System.out.println(xml);
    }

    @Test
    public void testXml2Member() {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<member><sid>10010</sid><sname>小黑</sname><dcourse>2500.0</dcourse></member>";
        Member member = Xml2Member(xml);
        System.out.println(member);
    }


    //把对象用dom4j转换为xml格式的数据（字符串）
    public static String Member2Xml(Member m) {
        //获取dom4j的Document对象
        Document doc = DocumentHelper.createDocument();
        //向document对象中添加一个标签(根标签，根节点)
        Element member = doc.addElement("member");
        //向根节点添加元素
        member.addElement("sid").setText(m.getSid());
        member.addElement("sname").setText(m.getSname());
        member.addElement("dcourse").setText(m.getCourse() + "");
        //把documet对象转换为xml格式，返回
        return doc.asXML();
    }

    //把xml格式的字符串数据，通过dom4j解析为相对应的对象
    public static Member Xml2Member(String xml) {
        Member member = new Member();
        //根据xml格式字符串获取document对象
        Document doc;
        try {
            doc = DocumentHelper.parseText(xml);
            //获取document对象的根节点
            Element root = doc.getRootElement();
            //获取根节点下的标签元素
            member.setSid(root.element("sid").getText());
            member.setSname(root.element("sname").getText());
            member.setCourse(Double.parseDouble(root.element("dcourse").getText()));
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return member;
    }


}
